package offer;

/**
 * 剑指 Offer 05. 替换空格
 */
public class ReplaceSpace {


    public static void main(String[] args) {
        String s = "We are happy.";
        String s1 = replaceSpace1(s);
        System.out.println(s1);
    }

    /**
     * 使用StringBuffer来实现字符串中空格的替换
     *
     * @param s
     * @return
     */
    public static String replaceSpace1(String s) {
        StringBuilder sb = new StringBuilder();
        char[] charArray = s.toCharArray();
        for (char c : charArray) {
            if (c == ' ') {
                sb.append("20%");
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }


    /**
     * 使用字符，1.先统计空字符长度 2.创建一个字符数组 3，遍历原始字符串。
     *
     * @param s
     * @return
     */
    public static String replaceSpace2(String s) {
        int num = 0;
        int length = s.length();
        for (int i = 0; i < length; i++) {
            char v = s.charAt(i);
            if (' ' == v) {
                num++;
            }
        }
        int newLength = s.length() + num * 2;
        char[] newChar = new char[newLength];
        int j = 0;
        for (int i = 0; i < newLength; i++) {
            if (j < length && ' ' == s.charAt(j)) {
                newChar[i] = '%';
                newChar[i + 1] = '2';
                newChar[i + 2] = '0';
                i = i + 2;
            } else {
                newChar[i] = s.charAt(j);
            }
            j++;
        }
        return new String(newChar);
    }


}
